package com.topisv.tms.platform.mls;

import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.topisv.tms.entity.Area;
import com.topisv.tms.entity.Customers;
import com.topisv.tms.entity.EdiOrder;
import com.topisv.tms.entity.EdiOrderItem;
import com.topisv.tms.entity.ShopSource;
import com.topisv.tms.entity.log.OrderLog;
import com.topisv.tms.repository.log.OrderLogDao;
import com.topisv.tms.rest.entity.Batch;
import com.topisv.tms.service.AreaService;
import com.topisv.tms.service.CustomersService;
import com.topisv.tms.service.EdiOrderService;
import com.topisv.tms.service.ShopSourceService;
import com.topisv.tms.service.work.WorkOrderService;
import com.topisv.tms.utils.SystemUtil;
import com.topisv.tms.utils.TimeUtil;
import com.topisv.tms.utils.http.HttpPost;
import com.topisv.tms.utils.rule.TMSRule;
import com.topisv.tms.utils.vo.RestAreaGroupVo;
import com.topisv.tms.utils.vo.RestCustomersAreagroupVo;

/**
 * 美丽说接口
 * 
 * @author calvin
 */
@Controller
@RequestMapping(value = "/api/mls")
public class MlsRestController {

	@Autowired
	private EdiOrderService ediOrderService;
	
	@Autowired
	private ShopSourceService shopSourceService;
	
	@Autowired
	private CustomersService customerService;
	
	@Autowired
	private AreaService areaService;
	
	//@Autowired
	//private ExceptionOrderService exceptionOrderService;
	
	@Autowired
	private CustomersService customersService;
	
	@Autowired
	private WorkOrderService workOrderService;
	
	@Autowired
	private OrderLogDao orderLogDao;
	
	
	@Autowired
	private TMSRule tmsRule;
	
	private static final Logger logger = LoggerFactory.getLogger(MlsRestController.class);
	

	@RequestMapping(value = "synOrder.py",method = RequestMethod.POST)
	public void create(@RequestParam(value = "appkey") String appkey,@RequestParam(value = "appsecret") String appsecret
			,@RequestParam(value = "data") String data,HttpServletRequest request,HttpServletResponse response) {
		
		Map map = new HashMap();
		ObjectMapper objectMapper = new ObjectMapper();
		JSONObject json=null;
		logger.info("美丽说同步订单appkey=" + appkey + ",appsecret=" + appsecret + ",data=" + data);
		Customers customers =null;
		String areaGroupCode = "";
		try
		{
			String md5 = SystemUtil.MD5(data + appkey);
			String base64 = SystemUtil.getBASE64(md5);
			if(!base64.equals(appsecret))
			{
				map.put("state", "false");
				map.put("reason", "签名验证失败");
			}
			else
			{
				ShopSource shopSource = null;
				
				shopSource = shopSourceService.findByHtShopId("MLS");
				
				if(null != shopSource)
				{
					json=JSONObject.fromObject(data);
					
					json = json.getJSONObject("orderInfo");
					EdiOrder ediOrder1 = ediOrderService.findByCustomerCodeAndFromno("MLS", json.getString("orderCode"));
					if(null == ediOrder1)
					{
						EdiOrder ediOrder = new EdiOrder();
						ediOrder.setCustomerCode("MLS");
						ediOrder.setShopCode(shopSource.getShopCode());
						ediOrder.setShopna(shopSource.getShopName());
						ediOrder.setErpType(shopSource.getOrdenoSourceCode());
						ediOrder.setPlatformCustomerCode(json.getString("customerCode"));
						ediOrder.setShopId("MLS");
						customers = customerService.findByCustomerCode(shopSource.getCustomerCode());
						if(null != customers)
						{
							RestCustomersAreagroupVo  vo = HttpPost.getRestCustomersAreagroupVo(customers);
							if(null != vo)
							{
								String province = json.getString("consigneeProvince");
								if("新疆维吾尔族自治区".equals(province))
								{
									province="新疆维吾尔自治区";
								}
								Area area = areaService.findByAreaName2(province + "%");
								if(null != area)
								{
									List<RestAreaGroupVo> restAreaGroupVo = vo.getRestAreaGroupDtos();
									for(RestAreaGroupVo ragVo : restAreaGroupVo)
									{
										String areaCodes = ragVo.getAreaCodes();
										if(areaCodes != null && areaCodes.indexOf(area.getAreaCode()) != -1)
										{
											areaGroupCode = ragVo.getAreagroupCode();
											break;
										}
									}
									if(!"".equals(areaGroupCode))
									{
										ediOrder.setAreaGroupCode(areaGroupCode);
										ediOrder.setProvco(area.getAreaCode());
									}
									else
									{
										map.put("state", "false");
										map.put("reason", "省份不在服务范围");
									}
									
								}
								else
								{
									map.put("state", "false");
									map.put("reason", "找不到省份区域");
								}
							}
							else
							{
								map.put("state", "false");
								map.put("reason", "找不到覆盖区域信息");
							}
						}
						else
						{
							map.put("state", "false");
							map.put("reason", "找不到客户信息");
						}
						
						if(null != map.get("state")  && !"".equals(map.get("state")))
						{
							try {
								objectMapper.writeValue(response.getWriter(), map);
							} catch (Exception e1) {
								logger.info("保存失败:" + map.get("state") + "--" + map.get("reason"));
							}
							return;
						}
						ediOrder.setWaybillNo(tmsRule.getNumber(customers.getCustomerCode()));
						ediOrder.setFromno(json.getString("orderCode"));
						ediOrder.setCustomerOrdeno(json.getString("orderCode"));
						ediOrder.setCrtime(TimeUtil.getDateMMSS(json.getString("createTime")));
						ediOrder.setOrderStatus(json.getString("orderStatus"));
						ediOrder.setRecena(json.getString("consigneeUser"));
						ediOrder.setPostco(json.getString("consigneeZip"));
						try {
							ediOrder.setTeleph(json.getString("consigneePhone"));
						} catch (Exception e2) {
							ediOrder.setTeleph("");
						}
						try {
							ediOrder.setMobile(json.getString("consigneeMobile"));
						} catch (Exception e2) {
							ediOrder.setMobile("");
						}
						ediOrder.setProvna(json.getString("consigneeProvince"));
						ediOrder.setCityna(json.getString("consigneeCity"));
						try {
							ediOrder.setDistna(json.getString("consigneeDistrict"));
						} catch (Exception e) {
							ediOrder.setDistna("");
						}
						ediOrder.setAddres(json.getString("consigneeAddress"));
						ediOrder.setSememo(json.getString("sellerMemo"));
						ediOrder.setBumemo(json.getString("buyerMemo"));
						ediOrder.setStatus("pending");
						ediOrder.setCacode("YTO");
						ediOrder.setOldCacode("YTO");
						ediOrder.setCaname("圆通速递");
						ediOrder.setActuallyPaid(Double.parseDouble(json.getString("payment")));
						
						List<EdiOrderItem> item = new ArrayList<EdiOrderItem>();
						JSONArray jsonArray = json.getJSONArray("goodsInfo");
						int sku_num = 0;
						if(null != jsonArray)
						{
							for(int i=0; i<jsonArray.size(); i++)
							{
								JSONObject jsonObject = (JSONObject)jsonArray.opt(i);
								EdiOrderItem ediOrderItemHT = new EdiOrderItem();
								ediOrderItemHT.setOrdeno(json.getString("orderCode"));
								ediOrderItemHT.setSku(jsonObject.getString("barcode"));
								ediOrderItemHT.setMidId(jsonObject.getString("mid"));
								ediOrderItemHT.setNam(jsonObject.getString("goodsName"));
								ediOrderItemHT.setQty(jsonObject.getInt("goodsNum"));
								ediOrderItemHT.setCrtime(new Date());
								ediOrderItemHT.setPri(Double.parseDouble(jsonObject.getString("salePrice")));
								ediOrderItemHT.setPay(Double.parseDouble(jsonObject.getString("salePrice")));
								ediOrderItemHT.setCustomerCode(ediOrder.getCustomerCode());
								if(ediOrderItemHT.getQty() > 0)
								{
									sku_num += jsonObject.getInt("goodsNum");
									item.add(ediOrderItemHT);
								}
							}
						}
						if(sku_num > 1)
						{
							ediOrder.setOrderType("multiple");
						}
						else if(sku_num == 1)
						{
							ediOrder.setOrderType("single");
						}
						ediOrder.setOrderStatus("ok");
						map.put("state", "true");
						map.put("reason", "接收成功");
						ediOrder.setSkuQty(sku_num);
						ediOrder.setSkulst(item);
						ediOrder.setAdtime(new Date());
						ediOrder.setPatime(new Date());
						try {
						
							logger.info("美丽说---订单流入");
							ediOrder=ediOrderService.saveEdiOrderPlat(ediOrder);
							if("cancel".equals(ediOrder.getStatus())||"no".equals(ediOrder.getOrderStatus())||"repeat".equals(ediOrder.getStatus())){
								map.put("state", "false");
								map.put("reason", ediOrder.getMessage());
							}
							/*else
							{
								try {
									OrderLog orderLog=new OrderLog(
											ediOrder.getOrdeno(),
											ediOrder.getCustomerCode(),
											"0", //操作类型 （1.创建批次 2.创建任务  3.拣货完成 4.包装完成 5.发货完成 6.签收完成 7.异常登记 8.完成灯光拣选任务 9.打印单据）
											null,
											new Date(),
											null,
											"系统接收订单");
									this.orderLogDao.save(orderLog);
								} catch (Exception e) {
								}
							}*/
						} catch (Exception e1) {
							// TODO Auto-generated catch block
							map.put("state", "false");
							map.put("reason", "保存失败");
							logger.error("保存订单失败", e1);
						}
					}
					else
					{
						map.put("state", "true");
						map.put("reason", "接收成功");
					}
					
				}
				else
				{
					map.put("state", "false");
					map.put("reason", "保存失败！");
				}
			}
			
		}
		catch(Exception e)
		{
			map.put("state", "false");
			map.put("reason", e.getMessage());
			logger.info("json格式错误==" , e);
		}
		try {
			objectMapper.writeValue(response.getWriter(), map);
			logger.info("返回结果:" + map.get("state") + "--" + map.get("reason"));
		} catch (Exception e1) {
		}
		
	}
	@RequestMapping(value = "synGoods",method = RequestMethod.POST)
	public void synGoods(@RequestParam(value = "appkey") String appkey,@RequestParam(value = "appsecret") String appsecret
			,@RequestParam(value = "data") String data,HttpServletRequest request,HttpServletResponse response) {
		
		Map map = new HashMap();
		ObjectMapper objectMapper = new ObjectMapper();
		Batch batch = null;
		logger.info("美丽说同步商品jsonData=" + data);
		JSONObject json=null;
		try
		{
			logger.info("美丽说同步商品jsonData=" + data);
			
			json=JSONObject.fromObject(data);
			
			json = json.getJSONObject("orderInfo");
			
			map.put("state", "true");
			map.put("reason", "接收成功");
			try {
				objectMapper.writeValue(response.getWriter(), map);
			} catch (Exception e1) {
				logger.info("json格式错误");
			}
		}
		catch(Exception e)
		{
			map.put("state", "true");
			map.put("reason", "接收成功");
			try {
				objectMapper.writeValue(response.getWriter(), map);
			} catch (Exception e1) {
				logger.info("json格式错误");
			}
			return;
		}
		
	}
	
	@RequestMapping(value = "cancelOrder.py",method = RequestMethod.POST)
	public void cancelOrder(@RequestParam(value = "appkey") String appkey,@RequestParam(value = "appsecret") String appsecret
			,@RequestParam(value = "data") String data,HttpServletRequest request,HttpServletResponse response) {
		
		Map map = new HashMap();
		JSONObject json=null;
		ObjectMapper objectMapper = new ObjectMapper();
		Batch batch = null;
		try
		{
			logger.info("美丽说取消订单appkey=" + appkey + ",appsecret=" + appsecret + ",data=" + data);
			String md5 = SystemUtil.MD5(data + appkey);
			String base64 = SystemUtil.getBASE64(md5);
			if(!base64.equals(appsecret))
			{
				map.put("state", "false");
				map.put("reason", "签名验证失败");
			}
			else
			{
				json=JSONObject.fromObject(data);
				
				String orderCode = json.getString("orderCode");
				EdiOrder ediOrder = ediOrderService.findByCustomerCodeAndFromno("MLS", orderCode);
				String ordeno = "";
				String type = json.getString("type");
				String barCode = "";
				if(ediOrder != null)
				{
					ordeno = ediOrder.getOrdeno();
					if("1".equals(type))
					{
						SystemUtil.pub("http://tms.paiu.com.cn/tms/api/mlsCancelOrder/create", "ordeno=" + ordeno + "&data=" + data);
					}
					else
					{
						workOrderService.cancelOrder(ediOrder.getOrdeno(),"ADMIN");
					}
					map.put("state", "true");
					map.put("reason", "取消成功");
				}
				else
				{
					map.put("state", "false");
					map.put("reason", "订单号不存在");
				}
				
			}
			
			try {
				objectMapper.writeValue(response.getWriter(), map);
			} catch (Exception e1) {
				logger.info("json格式错误");
			}
		}
		catch(Exception e)
		{
			map.put("state", "false");
			map.put("reason", e.getMessage());
			try {
				objectMapper.writeValue(response.getWriter(), map);
			} catch (Exception e1) {
				logger.info("json格式错误");
			}
			return;
		}
		
	}
	
	@RequestMapping(value = "returnGoods.py",method = RequestMethod.POST)
	public void returnGoods(@RequestParam(value = "appkey") String appkey,@RequestParam(value = "appsecret") String appsecret
			,@RequestParam(value = "data") String data,HttpServletRequest request,HttpServletResponse response) {
		
		Map map = new HashMap();
		ObjectMapper objectMapper = new ObjectMapper();
		JSONObject json=null;
		Batch batch = null;
		try
		{
			logger.info("美丽说退货appkey=" + appkey + ",appsecret=" + appsecret + ",data=" + data);
			String md5 = SystemUtil.MD5(data + appkey);
			String base64 = SystemUtil.getBASE64(md5);
			if(!base64.equals(appsecret))
			{
				map.put("state", "false");
				map.put("reason", "签名验证失败");
			}
			else
			{
				json=JSONObject.fromObject(data);
				
				String orderCode = json.getString("orderCode");
				EdiOrder ediOrder = ediOrderService.findByCustomerCodeAndFromno("MLS", orderCode);
				String ordeno = "";
				String type = json.getString("type");
				if(ediOrder != null)
				{
					ordeno = ediOrder.getOrdeno();
					
					SystemUtil.pub("http://tms.paiu.com.cn/tms/api/mlsReturnGoods/create", "ordeno=" + ordeno + "&data=" + data);
					map.put("state", "true");
					map.put("reason", "接收成功");
				}
				else
				{
					map.put("state", "false");
					map.put("reason", "订单号不存在");
				}
			}
			map.put("state", "true");
			map.put("reason", "接收成功");
			try {
				objectMapper.writeValue(response.getWriter(), map);
			} catch (Exception e1) {
				logger.info("json格式错误");
			}
		}
		catch(Exception e)
		{
			map.put("state", "false");
			map.put("reason", e.getMessage());
			try {
				objectMapper.writeValue(response.getWriter(), map);
			} catch (Exception e1) {
				logger.info("json格式错误");
			}
			return;
		}
		
	}
	
	@RequestMapping(value = "synOrder.py",method = RequestMethod.GET)
	public void synOrder2(HttpServletResponse response) {
		
		PrintWriter out = null;
		try {
			out = response.getWriter();
			out.write("success");
			out.close();
		} catch (Exception e) {
			logger.error("异常：",e);
		}
		
	}
	
	@RequestMapping(value = "cancelOrder.py",method = RequestMethod.GET)
	public void cancelOrder2(HttpServletResponse response) {
		
		PrintWriter out = null;
		try {
			out = response.getWriter();
			out.write("success");
			out.close();
		} catch (Exception e) {
			logger.error("异常：",e);
		}
		
	}
	
	@RequestMapping(value = "returnGoods.py",method = RequestMethod.GET)
	public void returnGoods2(HttpServletResponse response) {
		
		PrintWriter out = null;
		try {
			out = response.getWriter();
			out.write("success");
			out.close();
		} catch (Exception e) {
			logger.error("异常：",e);
		}
		
	}

}
